package com.fanyouzhao.ehome.web.servlet; /**
 * @Author: fanyouzhao
 * @Date: 15:06 2021/5/12
 */

import com.alibaba.fastjson.JSON;
import com.fanyouzhao.ehome.service.UserService;
import com.fanyouzhao.ehome.service.impl.UserServiceImpl;
import com.fanyouzhao.ehome.util.JsonResult;
import com.fanyouzhao.ehome.util.ResponseUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Random;

@WebServlet(name = "SmsServlet", value = "/sendCode")
public class SmsServlet extends HttpServlet {

    private final UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //中文处理
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        ((HttpServletResponse) response).setHeader("content-Type", "text/html;charset=UTF-8");

        JsonResult jsonResult = new JsonResult();
        jsonResult.setData(null);
        //获得手机号
        String phone = request.getParameter("phone");
        try {
            //如果该手机号未注册
            if (!userService.isReg(phone)) {
                /*生成随机数*/
                Random random = new Random();
                StringBuilder code = new StringBuilder();
                for (int i = 0; i < 6; i++) {
                    code.append(random.nextInt(9)+1);
                }
                /*调用发送短信方法，得到返回结果：OK*/
                //暂时注释
//                String s = AliMsm.sendMsg(phone, code.toString());
                String s = "OK";
                System.out.println("发送返回结果 = " + s);
                if ("OK".equals(s)) {
                    System.out.println("发送成功，验证码为：" + code);
                    /*存写验证码到session中*/
                    HttpSession session = request.getSession();
                    session.setAttribute("code",code);
                    jsonResult = new JsonResult("0","发送成功");
                } else {
                    jsonResult = new JsonResult("1","发送失败");
                }
            } else {
                jsonResult = new JsonResult("1","该手机号已注册！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        ResponseUtil.send(response, JSON.toJSONString(jsonResult.getValues()));

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
